package cn.pubinfo.controller;

import cn.pubinfo.model.User;
import cn.pubinfo.service.UserService;
import cn.pubinfo.util.BaseUtil;
import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * Created by zck on 2017/8/4.
 */
@Controller
@RequestMapping("user")
public class UserController {
    @Resource
    private UserService userService;
    @Resource
    private BaseUtil baseUtil;

    private Logger logger = Logger.getLogger(this.getClass());

    @ResponseBody
    @RequestMapping("login")
    public String login(User user, HttpServletRequest request) {
        if (user == null || user.getUsername() == null || user.getPassword() == null) {
            return "用户名和密码不能为空";
        }
        //验证是否已登录
        if (SecurityUtils.getSubject().isAuthenticated()) {
            return "success";
        }
        // 登陆验证
        UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(), user.getPassword().toCharArray(), null);
//        token.setRememberMe(true);
        try {
            SecurityUtils.getSubject().login(token);
        } catch (UnknownAccountException | IncorrectCredentialsException ex) {
            return "用户不存在或者密码错误";
        }
        String ip = baseUtil.getIpAddr(request);
        user.setLastLoginIp(ip);
        userService.updateLastLoginIp(user);
        logger.info("login--> user: " + user.getUsername());
        logger.info("login--> user ip: " + ip);
        return "success";
    }

    @ResponseBody
    @RequestMapping("logout")
    public String logout() {
        Subject subject = SecurityUtils.getSubject();
        logger.info("logout--> user: " + subject.getPrincipal());
        subject.logout();
        return "退出登陆！";
    }

    @ResponseBody
    @RequestMapping("add")
    @RequiresPermissions("add")
    @RequiresRoles("admin")
    public String add(User user, HttpServletRequest request) {
        //检查用户是否合法
        String msg = check(user);
        if (msg != null) {
            return msg;
        }
        //加盐
        String salt = new SecureRandomNumberGenerator().nextBytes().toHex();
        user.setSalt(salt);
        //密码加密
        String hashAlgorithmName = "MD5";
        int hashIterations = 5;
        String encryptedPassword = new SimpleHash(hashAlgorithmName, user.getPassword(), salt, hashIterations).toHex();
        user.setPassword(encryptedPassword);
        //注册ip
        String ip = baseUtil.getIpAddr(request);
        user.setRegIp(ip);
        if (userService.add(user) == 1) {
            return "添加成功";
        }
        return "添加失败!";
    }

    private String check(User user) {
        if (userService.getByUsername(user.getUsername()) != null) {
            return "用户名已存在!";
        }
        return null;
    }

    @ResponseBody
    @RequestMapping("del")
    @RequiresRoles("admin")
    public String del(String username) {
        return "del_success";
    }


    @ResponseBody
    @RequestMapping("test")
    public String test(int id){
        return userService.getById(id).getUsername();
    }
}
